#ifndef __CHAR_LIST_H__
  #define __CHAR_LIST_H__

#include "char_node.h"

namespace char_memory_management {

//! A simple list for char_instance_manager

/*!
A minimal list implementation for char_instance_manager.
*/

  class char_list {
  private:
    const char_node *head;
    unsigned int free_size; // the most free node in the list

    //! assignment operator: not allowed
    char_list &operator=(const char_list &l);

    //! copy constructor: not allowed
    char_list(const char_list &l);

  public:
    //! returns the head of the list
    const char_node *get_head() const {
      return this->head;
    } // get_head

    //! adds a new element to the begining of the list
    void prepend(char_node *element) {
      if (element != 0) {
        free_size = max(free_size, element->get_free_size());

        element->set_next(this->head);
        this->head = element;
      } // if
    } // prepend

    //! releases the whole list
    void release() {
      while (this->head != 0) {
        char_node *temp = const_cast<char_node*>(head);
        head = head->get_next();

        delete temp;
        temp = 0;
      } // while
    } // release

    //! returns a char_node, which is large enough for the requested size. Or 0 will be returned if no suitable char_node could be found
    const char_node *find_the_suitable_node(unsigned int size) {
      if (free_size < size)
        return 0; // no need to search, size is not available anyway

      const char_node *temp = this->head;

      while (temp != 0) {
        if (temp->get_free_size() > size)
          return temp;
        else
          temp = temp->get_next();
      } // while

      if (size != 0)
        free_size = size - 1; // optimization

      return 0; // return 0 if no node has enough place available
    }

    //! default constructor
    char_list() : head(0), free_size(0) {
      // nothing to do
    } // char_list

    //! destructor (non-virtual: please do not inherit from this class)
    ~char_list() {
      release();
    } // ~char_list

  }; // class char_list

} // namespace char_memory_management

#endif
